<?php

class Admin_purchaseController extends Admin_baseController {
    /**
     * 补货
     */
    public function editAction()
    {
        $shop_id = self::$admin_info['shop_id'];//经销商id
        if (!$shop_id) {
            Response::showMsg('不是经销商账号登陆，无法操作');
        }

        $good_id = Request::getParams('good_id');
        $attribute_id = Request::getParams('attributes_id');

        $data['attribute_id'] = $attribute_id;

        $goods_info = self::model('goods')->getOne('goods_id=?',$good_id);
        $data['good_id'] = $good_id;
        $data['good_name'] = $goods_info['name'];
        $data['good_image'] = $goods_info['image'];
        $data['price'] = self::model('dealer_goods')->goodsPrice(['goods_id'=>$good_id,'attribute_id'=>$attribute_id,'dealer_id'=>$shop_id]);

        $attribute_info = self::model('goods_attribute')->getOne('attribute_id=?',$attribute_id);
        $data['attribute_name'] = $attribute_info['name'];

        $dealer_info = self::model('dealer')->getOne('id=?', $shop_id);
        if (!$dealer_info['province'] || !$dealer_info['city'] || !$dealer_info['area'] || !$dealer_info['address']) {
            Response::showMsg('请去店铺设置填写收货地址');
        }
        $shop_province = self::model('region')->getOne('id=?',$dealer_info['province']);
        $data['province'] = $shop_province['name'];
        $shop_city = self::model('region')->getOne('id=?',$dealer_info['city']);
        $data['city'] = $shop_city['name'];
        $shop_area = self::model('region')->getOne('id=?',$dealer_info['area']);
        $data['area'] = $shop_area['name'];

        $data['get_address'] = $data['province'].$data['city'].$data['area'].$dealer_info['address'];

        $data['mobile'] = $dealer_info['mobile'];
        $data['responsible'] = $dealer_info['responsible'];

        $this->assign(array(
            'data' => $data
        ));
        $this->display();
    }

    /**
     * 购买，生成订单
     */
    public function confirmAction()
    {
        $shop_id = self::$admin_info['shop_id'];//经销商id
        if (!$shop_id) {
            Response::showMsg('不是经销商账号登陆，无法操作');
        }
        $good_id = Request::getParams('good_id');
        $attribute_id = Request::getParams('attribute_id');
        $buy_num = Request::getParams('buy_num');

        if (!is_numeric($buy_num) || strpos($buy_num*100,'.') !== false) {
            Response::showMsg('请输入正确的购买数量');
        }
        $kucun = self::model('goods_specification')->getOne(['goods_id=?','attributes_id1=?','admin_id=?'],[$good_id,$attribute_id,0]);
        if ($buy_num > $kucun['stock_total']) {
            Response::showMsg('库存不足，请联系品牌商');
        }

        $dealer_info = self::model('dealer')->getOne('id=?', $shop_id);

        $goods_info = self::model('goods')->getOne('goods_id=?',$good_id);

        $attribute_info = self::model('goods_attribute')->getOne('attribute_id=?',$attribute_id);

        $province = self::model('region')->getOne('id=?',$dealer_info['province']);
        $city = self::model('region')->getOne('id=?',$dealer_info['city']);
        $area = self::model('region')->getOne('id=?',$dealer_info['area']);

        $get_address = $province['name'].$city['name'].$area['name'].$dealer_info['address'];

        //减库存
        if ($kucun) {
            $stock = self::model('goods_specification')->update(
                ['stock_total'=>($kucun['stock_total']-$buy_num)],
                'specification_id=?',
                $kucun['specification_id']);
            if (!$stock) {
                Response::showMsg('库存修改失败');
            }
        }

        //生成订单与订单详情
        $price = self::model('dealer_goods')->goodsPrice(['goods_id'=>$good_id,'attribute_id'=>$attribute_id,'dealer_id'=>$shop_id]);
        $order_no = $this->generation();
        $order_info = [
            'dealer_id' => $shop_id,
            'good_id' => $good_id,
            'attribute_id' => $attribute_id,
            'buy_num' => $buy_num,
            'price' => $price,
            'pay_price' => 0,
            'total_price' => $buy_num * $price,
            'order_no' => $order_no,
            'pay_status' => 0,
            'order_status' => 0,
            'add_time' => time()
        ];

        $detail_order_id = self::model('dealer_order')->insert($order_info, true);
        if ($detail_order_id) {
            $detail = [
                'order_id' => $detail_order_id,
                'name' => $dealer_info['name'],
                'mobile' => $dealer_info['mobile'],
                'responsible' => $dealer_info['responsible'],
                'province' => $dealer_info['province'],
                'city' => $dealer_info['city'],
                'area' => $dealer_info['area'],
                'address' => $dealer_info['address'],
                'get_address' => $get_address,
                'good_name' => $goods_info['name'],
                'good_image' => $goods_info['image'],
                'attribute_type' => $attribute_info['type'],
                'attribute_name' => $attribute_info['name']
            ];
            self::model('dealer_order_detail')->insert($detail);
        }

        Response::ajax(200,'',['order_no'=>$order_no]);
    }

    /**
     * 支付
     */
    public function payAction()
    {
        $shop_id = self::$admin_info['shop_id'];//经销商id
        if (!$shop_id) {
            Response::showMsg('不是经销商账号登陆，无法操作');
        }

        $order_no = Request::getParams('order_no');
        if (!$order_no) {
            Response::showMsg('信息查询失败，请稍后重试');
        }
        if (!$order = self::model('dealer_order')->getOne('order_no=?', $order_no)) {
            Response::showMsg('订单不存在');
        }
        if (!$order_detail = self::model('dealer_order_detail')->getOne('order_id=?', $order['id'])) {
            Response::showMsg('订单详情不存在');
        }

        if ($order['pay_status'] != dealer_orderModel::ORDER_STATUS_UNPAY) {
            Response::showMsg('订单状态不对');
        }

        // 生成支付二维码
        require_once APP_ROOT."/lib/php_sdk/lib/WxPay.Api.php";
        require_once APP_ROOT."/lib/php_sdk/example/WxPay.NativePay.php";

        $notify = new NativePay();

        $amount = $order['total_price'];
        $body = '经销商扫码支付';
        $total_fee = intval(doubleval($amount)*100);
        $product_id = $order['dealer_id'].'_'.$order['good_id'].'_attribute_id';
        $attach = '';
        $out_trade_no = $order['order_no'];

        $input = new WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetAttach($attach);
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://".$_SERVER['SERVER_NAME']."/wx/notify");//这里写你的回调地址
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($product_id);

        $result = $notify->GetPayUrl($input);
        if (isset($result['return_code']) && $result['return_code'] == 'FAIL') {
            Response::showMsg('生成微信支付码错误：'.$result['return_msg']);
        }
        $code_url = $result["code_url"];

        $this->assign(array(
            'order' => $order,
            'order_detail' => $order_detail,
            'code_url' => $code_url
        ));
        $this->display();
    }

    /**
     * ajax查询支付成功后做跳转
     */
    public function payResultAction()
    {
        $order_no = Request::getParams('order_no');
        if (!$order_no) {
            Response::showMsg('信息查询失败，请稍后重试');
        }
        if (!$order = self::model('dealer_order')->getOne('order_no=?', $order_no)) {
            Response::showMsg('订单不存在');
        }

        if ($order['pay_status'] == 1) {
            Response::ajax(200,'支付成功,即将跳转...',['url' => Router::getBaseUrl().'/admin_dealer_order/list']);
        }
        Response::showMsg('等待...');
    }

    /**
     * 生成订单号
     * @return string
     */
    private function generation()
    {
        //订购日期
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）

        $order_id_main = date('mdHis',SYS_TIME) . rand(100000, 999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);

        $order_id_sum = 0;

        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i,1));
        }

        //生成校验码CC
        $order_cc = str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);

        //唯一订单号码（TTYYYYMMDDHHIISSNNNNNNNNCC）

        $order_SN = 100 . $order_id_main . $order_cc;

        return $order_SN;
    }

}